package com.leemz.netty.im;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * netty服务端最简化的启动流程
 */
public class SimpleNettyServer {

    public static void main(String[] args) {
        //两个线程模型组，相当于传统socket模型中的两个线程组，一个用来接受链接
        //另一个用来处理每条链接的数据读写io
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        //启动引导类
        ServerBootstrap bs = new ServerBootstrap();
        bs.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {

                    }
                });
        //绑定到指定端口，该操作是异步的。可以通过future监听回调来判断是否绑定成功
        bind(bs, 1000);
    }

    private static void bind(final ServerBootstrap bootstrap, final int port) {
        bootstrap.bind(port).addListener(future -> {
            if(future.isSuccess()) {
                System.out.println("端口在" + port + "绑定成功！");
            } else {
                System.out.println("端口在" + port + "绑定失败!");
                bind(bootstrap, port + 1);
            }
        });
    }

}
